<?php
/**
 * +------------------APP 用户信息基类---------------+
 * --------------------------------------------------+
 * +-----------用户信息的获取------------------------+
 * +-------------------------------------------------+
 * +-@author susy.liang <liangling@ilongyuan.com.cn>-+
 * +-------------------------------------------------+
 */
namespace Api\Controller;
use Api\Event\CacheEvent;
use Common\Util\aliyun\STS;

use Think\Upload\Driver\Ucloud;

class UserController extends UserBaseController {

	/**
	 * 个人资料设置的项限制
	 */
	protected $profileField = array(
		'game', 'desc', 'gender', 'age', 'address', 'stars', 'interest', 'turtial'
	);

	/**
	 * 基础参数的初始化
	 */
	protected function _initialize() {

		parent::_initialize();

	}

	/**
	 * 修改密码
	 */
	public function resetPwd() {
		$data = I('');
		unset($data['appToken']);

		$baseObj = A('Api/User', 'Event');
		$res = $baseObj->resetPwd(UID, $data);

		$this->ajaxReturn($res);
	}

	/**
	 * 人物头像修改
	 * ----------------------
	 * 头像文件的键名须为avatar
	 * ----------------------
	 */
	public function avatar() {
		// 头像
		$this->checkAuth('avatar');
		/* 调用文件上传组件上传文件 */
		$Picture = D('Api/Picture');
		$picDriver = C('PICTURE_UPLOAD_DRIVER');
		\Think\Log::record("[DEBUG] -- [UPLOAD] -- CONFIG: ". json_encode($picDriver), 'DEBUG');
		$info = $Picture->upload(
			$_FILES,
			C('PICTURE_UPLOAD'),
			C('PICTURE_UPLOAD_DRIVER'),
			C("UPLOAD_{$picDriver}_CONFIG")
		);
		 
		\Think\Log::record("[DEBUG] -- [UPLOAD] -- INFO: ". json_encode($info), 'DEBUG');
		/* 记录图片信息 */
		if ($info) {
			$avatar = $info['avatar']['path'];
			uri_format($avatar);
			if (service('Users')->where(array('id' => UID))->save(array('avatar' => $avatar))) {
				\Think\Log::record("[DEBUG] -- [UPLOAD] -- SAVE_SQL: ". service('Users')->_sql(), 'DEBUG');
				$score = event('Score')->get(UID, 'avatar');
				$data = array('avatar' => $avatar);
				$score != false && $data['score_plus'] = $score;
				$this->ajaxReturn(array('data' => $data, 'code' => self::$API_ERROR['SUCCESS'], 'info' => '上传成功'));
			} else {
				$this->ajaxReturn(array('data' => null, 'code' => self::$API_ERROR['SERVER'], 'info' => '头像保存失败'));
			}

		} else {
			$error = $Picture->getError();
			\Think\Log::record("[DEBUG] -- [UPLOAD] -- ERROR: ". $error, 'DEBUG');
			$this->ajaxReturn(array('data' => null, 'code' => self::$API_ERROR['SERVER'], 'info' => $error));
		}

	}

	/**
	 * 头像背景上传
	 */
	public function background() {
		// 权限
		$this->checkAuth('background');
		/* 调用文件上传组件上传文件 */
		$Picture = D('Api/Picture');
		$picDriver = C('PICTURE_UPLOAD_DRIVER');
		$info = $Picture->upload(
			$_FILES,
			C('PICTURE_UPLOAD'),
			C('PICTURE_UPLOAD_DRIVER'),
			C("UPLOAD_{$picDriver}_CONFIG")
		);

		/* 记录图片信息 */
		if ($info) {
			$backImg = $info['backImg']['path'];
			if (service('Users')->where(array('id' => UID))->save(array('background' => $backImg))) {
				uri_format($backImg);
				$score = event('Score')->get(UID, 'bg');
				$data = array('backImg' => $backImg);
				$score != false && $data['score_plus'] = $score;
				$this->ajaxReturn(array('data' => $data, 'code' => self::$API_ERROR['SUCCESS'], 'info' => '上传成功'));
			} else {
				$this->ajaxReturn(array('data' => null, 'code' => self::$API_ERROR['SERVER'], 'info' => '背景保存失败'));
			}

		} else {
			$error = $Picture->getError();
			$this->ajaxReturn(array('data' => null, 'code' => self::$API_ERROR['SERVER'], 'info' => $error));
		}

	}

	/**
	 * 设置用户昵称
	 */
	public function setNickname() {
		$nickname = I('nickname', '', 'strip_tags');
		$baseObj = A('Api/User', 'Event');
		$res = $baseObj->setNickname(array('nickname' => $nickname, 'uid' => UID));
		$this->ajaxReturn($res);
	}

	/**
	 * 用户注销
	 */
	public function logout() {
		$token = trim(I('appToken', '', 'strip_tags'));
		empty($token) && $this->ajaxReturn(array('data' => null, 'code' => self::$API_ERROR['PARAM'], 'info' => '参数错误'));
		$flg = service('Token')->logout($token);
		$code = self::$API_ERROR['SERVER'];
		switch ($flg) {
		case 1:
			$code = self::$API_ERROR['SUCCESS'];
			$errmsg = '注销成功';
			break;
		case -1:
			$code = self::$API_ERROR['PARAM'];
			$errmsg = '无效token';
			break;
		case -2:
			$errmsg = '请不要重复操作';
			break;
		case -3:
			$errmsg = '注销失败';
			break;
		default:
			$errmsg = '未知错误';
			break;
		}
		$this->ajaxReturn(array('data' => null, 'code' => $code, 'info' => $errmsg));
	}

	/**
	 * 会员中心信息的获取
	 */
	public function ucenter() {
		$baseObj = A('Api/User', 'Event');
		$user = $baseObj->detail(UID, true, '', true);
		$more = I('more');
		if ($more) {
			$more = explode(',', $more);
			foreach ($more as $field) {
				$data = $baseObj->getMoreField(UID, $field);
				$data && $user['more'][$field] = $data;
			}
		}

		if ($user) {
			// 登录任务 liubo 2016-8-19
			event('score')->get($user['id'], 'login');

			$mail_news = event('Mail')->isNew(UID);
			$mEvent = event('Message');

			$about_news = $mEvent->getNewCount(UID, ['at']) > 0;
			$notice_news = $mEvent->getNewCount(UID, ['zan', 'comment', 'like_user', 'follow']) > 0;
			$user['news'] = [
				'mail' => (int) $mail_news,
				'about' => (int) $about_news,
				'notice' => (int) $notice_news,
			];
			$videoCount = event('Video')->total(['uid' => UID]);
			$user['myVideos'] = (int) $videoCount;

			$user_pay_pwd = D('Common/PayUser')->where(['uid' => UID])->getField('password');
			$user['pay_password_setted'] = !empty($user_pay_pwd) ? 1 : 0;

			// 查询红点内容
			$cache = CacheEvent::instance(4);
			$key = 'IMBA.USER.REDDOT.';
			$reddot = $cache->hGetAll($key.UID)?:[];
			$reddot_common = $cache->hGetAll($key.'0')?:[];

			$user['reddot'] = array_merge($reddot, $reddot_common);
		}

		$this->ajaxReturn(array('data' => $user, 'code' => self::$API_ERROR['SUCCESS'], 'info' => '操作成功'));
	}

	/**
	 * 设置用户的资料
	 */
	public function setProfile() {
		$data = I('');
		unset($data['appToken']);
		unset($data['platform']);
		foreach ($data as $key => $value) {
			if (!in_array($key, $this->profileField)) {
				$this->error(self::$API_ERROR['PARAM'], '参数项有误');
			}
			if ($key == 'game') {
				$game = json_decode($value, true);
				$data[$key] = implode(',', $game);
			}
		}
		$ret = [];
		A('Api/User', 'Event')->setProfile(UID, $data, $ret);
		$this->success('设置成功', $ret);
	}

	/**
	 * 用户个人资料信息
	 */
	public function profile() {
		$user = A('Api/User', 'Event')->info(UID, true);
		$this->success('操作成功', $user);
	}

	/**
	 * 用户的浏览记录
	 */
	public function history() {

		$hEvent = A('Api/History', 'Event');

		$total = $hEvent->total(UID);
		if ($total) {
			$p = I('p', 1, 'intval');
			$pager = I('pager', C('HOME_VIDEO_PER', NULL, 10), 'intval');
			$infos = $hEvent->getLists(UID, $pager, $p);

			$details = array();
			$vEvent = A('Api/Video', 'Event');
			foreach ($infos as $key => $value) {
				$video = $vEvent->detail($value['video_id'], UID);
				if ($video) {
					$video['watch_time'] = $value['create_time'];
					$details[] = $video;
				}
			}
		}

		$data = array(
			'list' => $details,
			'total' => $total,
		);
		$this->success('操作成功', $data);
	}

	/**
	 * 用户的收藏列表信息
	 */
	public function favour() {

		$fEvent = A('Api/Favour', 'Event');

		$type = I('type', 'video', 'strip_tags');
		$type = $type == 'video' ? 0 : 1;

		$total = $fEvent->uTotal(UID, $type);
		if ($total) {
			$p = I('p', 1, 'intval');
			$pager = I('pager', C('HOME_VIDEO_PER', NULL, 10), 'intval');
			$lists = $fEvent->get(UID, $p, $pager, $type);

			$details = array();
			$vEvent = A('Api/Video', 'Event');
			foreach ($lists as $key => $value) {
				$video = $vEvent->detail($value['video_id'], UID);
				if ($video) {
					$video['favour_time'] = $value['create_time'];
					$details[] = $video;
				}
			}

		}

		$data = array(
			'list' => $details,
			'total' => $total,
		);

		$this->success('操作成功', $data);
	}

	/**
	 * 用户反馈类型
	 *@author zhaowei
	 */
	public function feedbackType() {
		$data = C('FEEDBACK_TYPE');
		$this->ajaxReturn(array('data' => $data, 'code' => self::$API_ERROR['SUCCESS'], 'info' => ''));
	}

	/**
	 * 用户反馈
	 *@author zhaowei
	 */
	public function feedback() {
		if (A('Api/Feedback', 'Event')->add(UID, I('type'), I('content'), I('platform'))) {
			$this->ajaxReturn(array('code' => self::$API_ERROR['SUCCESS'], 'info' => '操作成功'));
		} else {
			$this->ajaxReturn(array('code' => self::$API_ERROR['SERVER'], 'info' => '操作失败'));
		}
	}

	############################## FROM 2015-9-23 17:37:344 Legend. ########################

	// 用户签到
	public function sign() {
		$res = event('Sign')->check(UID);
		$res ? $this->success('签到成功', ['score_plus' => $res]) : $this->error(self::$API_ERROR['SIGN']);
	}

	/**
	 * [积分记录列表]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param
	 * @return
	 */
	public function scoreLog($p = 1, $pager = 10) {
		$p = $p >= 1 ? $p : 1;
		$pager = $pager >= 1 ? $pager : 10;
		$offset = ($p - 1) * $pager;
		$map['uid'] = UID;
		$list = service('ScoreLog')->where($map)->order('id desc')->limit("$offset, $pager")->select();
		$list = field_filter($list, ['action', 'score', 'memo', 'date'], true);
		$this->list_success($list);
	}

	// 用户上下线的经验处理
	public function onoff($sign = '', $online = 1, $ping = '', $type = 'mobile') {
		if (!$sign) {
			return $this->param_error();
		}

		if (!in_array($type, ['mobile', 'pc'])) {
			return $this->param_error();
		}

		$param = [
			'online' => $online,
			'appToken' => I('appToken'),
			'type' => $type,
		];

		$online == 0 && $param['ping'] = $ping;
		$this->checkSign($param, $sign);
		$event = event('User');
		if ($online) {
			$ping = $event->setOnline(UID, $type);
			$this->success('上线成功', ['ping' => $ping]);
		} else {
			$event->setOffline(UID, $type, $ping);
			$this->success('下线成功');
		}
	}

	// 修改语音签名
	public function voice() {
		if (!IS_POST || !$_FILES['voice']) {
			$this->param_error();
		}

		// 权限
		$this->checkAuth('voice');
		// 只接受post

		$File = D('Home/File');
		$pic_driver = C('SOUNDS_UPLOAD_DRIVER');
		$info = $File->upload(
			$_FILES,
			C('SOUNDS_UPLOAD'),
			C('SOUNDS_UPLOAD_DRIVER'),
			C("UPLOAD_{$pic_driver}_CONFIG")
		); //TODO:上传到远程服务器
		/* 记录图片信息 */
		if ($info) {
			uri_format($info['voice']['path']);
			$voice = $info['voice']['path'];
			$data = [];
			event('User')->setVoice(UID, $voice, $data);
			$data['uri'] = $voice;
			$this->success('设置成功', $data);
		} else {
			$this->error(self::$API_ERROR['META'], $File->getError());
		}

	}

	// 计算一次用户分享的接口
	public function share() {
		$type = I('type', '', 'trim');
		$id = I('id', 0, 'intval');
		$res = event('User')->share(UID, $type, $id);
		$this->success('分享成功', ['score_plus' => intval($res)]);
	}

	public function upload_video() {
		if (!IS_POST || !$_FILES['video']) {
			$this->param_error();
		}

		$File = D('Home/File');
		$pic_driver = C('VIDEO_UPLOAD_DRIVE');
		$info = $File->upload(
			$_FILES,
			C('VIDEO_UPLOAD'),
			C('VIDEO_UPLOAD_DRIVE'),
			C("UPLOAD_{$pic_driver}_CONFIG")
		); //TODO:上传到远程服务器
		/* 记录图片信息 */
		if ($info) {
			uri_format($info['video']['path']);
			$data['path'] = $info['video']['path'];
			$this->success('', $data);
		} else {
			$this->error(self::$API_ERROR['META'], $File->getError());
		}
	}

	public function upload_video_pic() {
		if (!IS_POST || !$_FILES['pic']) {
			$this->param_error();
		}

		$File = D('Home/Picture');
		$pic_driver = C('PICTURE_UPLOAD_DRIVER');
		$info = $File->upload(
			$_FILES,
			C('PICTURE_UPLOAD'),
			C('PICTURE_UPLOAD_DRIVER'),
			C("UPLOAD_{$pic_driver}_CONFIG")
		); //TODO:上传到远程服务器
		/* 记录图片信息 */
		if ($info) {
			uri_format($info['pic']['path']);
			$data['path'] = $info['pic']['path'];
			$this->success('', $data);
		} else {
			$this->error(self::$API_ERROR['META'], $File->getError());
		}
	}

	// OSS临时授权
	public function ossToken() {
		return;
		$Cache = event('Cache');
		$datetime = date('Y-m-d H:i:s');
		// $token = $Cache->get('OSS.TOKEN');
		if (!$token) {
			$STS = new STS();
			$token = $STS->getRole(UID);
			if ($token) {
				// $Cache->set('OSS.TOKEN', $token, 3600);
			}
		}
		$res['token'] = $token;
		$res['expire_in'] = 3600;
		$res['server_datetime'] = $datetime;
		$token ? $this->success('', $res) : $this->error(self::$API_ERROR['SERVER'], 'get oss token error');
	}


	public function ucloudToken()
	{
		$Ucloud = new Ucloud(C('VIDEO_UPLOAD.rootPath'), C('UPLOAD_UCLOUD_VIDEO_CONFIG'));
		$file = I('file');
		$mimetype = I('mimetype');
		$ua = I('ua');
		$method = I('method');

		if (strtolower($method) == 'delete') {
			$this->error(self::$API_ERROR['SERVER'], 'request forbidden');
		}

		$bucket = I('bucket');
		if (!$bucket && !empty(I('type'))){
			$type = I('type','image', 'trim');
			if ($type == 'image'){
				$bucket = C('UPLOAD_UCLOUD_CONFIG.bucket');
			}elseif ($type == 'video'){
				$bucket = C('UPLOAD_UCLOUD_VIDEO_CONFIG.bucket');
			}else{
				$this->error(self::$API_ERROR['SERVER'], 'param error');
			}
		}
		$token = $Ucloud->sign($file, $mimetype, $ua, $method, $bucket);
		$res['token']  = $token;
		$res['bucket'] = $bucket;
		$res['file']   = $file;
		$token ? $this->success('', $res) : $this->error(self::$API_ERROR['SERVER'], 'get ucloud token error');
	}


	public function zone() {
		echo date('Y-m-d H:i:s');
	}

	private function computeSignature($parameters, $accessKeySecret) {
		ksort($parameters);
		$canonicalizedQueryString = '';
		foreach ($parameters as $key => $value) {
			$canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value);
		}
		$stringToSign = 'GET' . '&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
		$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret, true));

		return $signature;
	}

	protected function percentEncode($str) {
		$res = urlencode($str);
		$res = preg_replace('/\+/', '%20', $res);
		$res = preg_replace('/\*/', '%2A', $res);
		$res = preg_replace('/%7E/', '~', $res);
		return $res;
	}

	################## FROM 2016-03-10 19:48:52 Legend.Xie ##############

	// 返回接收到的消息列表
	public function notice() {
		$default_pager = 10;
		$p = I('p', 1, 'intval');
		$p = $p ?: 1;
		$pager = I('pager', $default_pager, 'intval');
		$lists = event('UserNotice')->getLists(UID, $p, $pager);
		$lists = field_filter($lists, ['id', 'type', 'create_time', 'status', 'data', 'content'], true);

		// 设置为已读 liubo 2016-07-12
		event('message')->setRead(UID, ['type' => ['in', ['comment', 'zan', 'follow', 'like_user']]]);
		foreach ($lists as $key => &$value) {
			$value['title'] = '66Play';
			$value['format_time'] = unixtime_format($value['create_time']);
			if (empty($value['data']))
			{
				unset($value['data']);
			}
		}
		// lists_format($lists, [], true);
		$this->list_success($lists);
	}

	// 给工具返回的推送消息的内容
	// 请求之后返回数据并且清除redis列表
	public function pushNotice() {
		$cache = CacheEvent::instance(4);
		$key = "IMBA.PUSH.TOOL.UID." . UID;
		$count = $cache->lSize($key);
		for ($i = 0; $i < $count; $i++) {
			$data = $cache->lPop($key);
			$data = json_decode($data, true);
			!empty($data['event_id']) && $data['uri'] = U('/Home/Share/video', ['id' => $data['event_id']], true, true);

			if (!empty($data['sender_id'])){
				$data['user'] = event('User')->info($data['sender_id']);
			}

			$lists[] = array_filter_by_array($data, ['event_id', 'uri', 'type', 'content', 'sender_name', 'user']);
		}
		$this->list_success($lists);
	}


	// 返回用户上传的视频信息
	public function myVideos()
	{
		$query = ['uid' => (int)UID];
		$p = I('p', 1, 'intval');
		$p = $p > 0 ? $p : 1;
		$pager = I('pager', 10, 'intval');
		$offset = ($p - 1)*$pager;
		$limit = "$offset, $pager";
		$ids = event('Video')->lists($query, $limit, false, true);

		$filter_map = ['id', 'title', 'type', 'thumb', 'pre_uri', 'uri', 'dpi_levels', 'time', 'detail', 'create_time', 'game_id', 'game', 'uid', 'user', 'statis', 'tags', 'action', 'icons', 'status'];
		$videos = $this->lists_format($ids, $filter_map);
		$res = [
			'count' => count($videos),
			'lists' => $videos ?: [],
			'total' => event('Video')->total($query)
		];
		return $this->success('', $res);
		// return $this->list_success($videos);
	}

	public function dailyTask()
	{
		event('score')->get(UID, 'login');
		$data = event('score')->dailyTask(UID);
		$data['description'] = C('TASK_DESCRIPTION');
		$this->success('', $data);
	}

	/**
	 * 用户任务上报
	 * @author liubo <liubo@ilongyuan.com.cn>
	 */
	public function task_report() {
		$res = event('score')->get(UID, I('action', '', 'trim'));
		$this->success('请求成功', ['score_plus' => intval($res)]);
	}
}
